/* eslint-disable default-case */
import { message } from 'antd';
import {
  protocolList,
  protocolUpdateStatus,
  protocolDetail,
  protocolProductList,
  protocolAdd,
  protocolUpdate,
  protocolHistory,
  protocolAreaList,
  getDownloadInfo,
  uploadFile,
} from '@/services/supplymanage';
import { getArryStringBySymbol } from '@/utils/utils';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'protocol';
const ModelAddEmp = {
  namespace,
  state: {
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    detail: {
      detList: [],
      affixList: [],
    },
    addOrEdit: {
      productList: [],
    },
    history: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    modalData: {},
    formFieldsValue: {},
    expandForm: false,
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/nsApi/suppProto/dowoloadErrorExist', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    valuesArr: ['suppProtName', 'recvSuppId', 'custId', 'areaId'],
  },
  effects: {
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(protocolList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    // 更新状态：废弃
    *updateStatus({ payload, callback }, { call }) {
      const response = yield call(protocolUpdateStatus, payload);
      if (callback) callback(response);
    },
    // 获取详情数据
    *fetchDetail({ payload, callback }, { call, put }) {
      const response = yield call(protocolDetail, payload);
      if (response.success) {
        const areaIdList = [];
        response.data.areaList.forEach(item => {
          areaIdList.push(item.areaId);
        });
        const res = yield call(protocolProductList, {
          suppId: response.data.recvSuppId,
          areaIdList,
        });
        yield put({
          type: 'getDetail',
          payload: { detailData: response.data, productData: res.data },
        });
        if (callback) callback(response.data);
      }
    },
    // 获取供应商范围地区列表
    *fetchAreaList({ payload }, { call }) {
      const response = yield call(protocolAreaList, payload);
      return response;
    },
    // 获取产品列表数据
    *fetchProductList({ payload }, { call, put }) {
      const response = yield call(protocolProductList, payload);
      if (response.success) {
        yield put({
          type: 'getProductList',
          payload: response.data,
        });
      }
    },
    // 添加数据
    *addList({ payload, callback }, { call, put }) {
      const response = yield call(protocolAdd, payload);
      if (response.success) {
        yield put({
          type: 'clearData',
          payload: {},
        });
      }
      if (callback) callback(response);
    },
    // 添加数据
    *updateList({ payload, callback }, { call, put }) {
      const response = yield call(protocolUpdate, payload);
      if (response.success) {
        yield put({
          type: 'clearData',
          payload: {},
        });
      }
      if (callback) callback(response);
    },
    // 获取操作历史
    *fetchHistory({ payload }, { call, put }) {
      const response = yield call(protocolHistory, payload);
      const {
        pagerArg: { currentPage, pageSizes },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getHistory',
          payload: {
            data: response.data,
            currentPage,
            pageSizes,
          },
        });
      }
    },
    // 获取fileId，fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      } else {
        message.warning(`${response.message || '服务端错误：获取下载模板失败！'}`);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
      function* ({ payload }, { call, put }) {
        try {
          const response = yield call(uploadFile, payload);
          if (response.success) {
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      { type:'throttle' , ms :10000 }
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.protocol);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      list.forEach(item => {
        const temp = item;
        temp.areaNameList = getArryStringBySymbol(temp.areaList, 'areaName');
        temp.packList.forEach(priceitem => {
          const ptemp = priceitem;
          ptemp.price = ptemp.detList.reduce(
            (total, currentValue) => total + currentValue.price || total + currentValue.fee || 0,
            0
          );
          ptemp.pdNameList = getArryStringBySymbol(ptemp.detList, 'pdName', '+');
        });
        temp.money = 0;
        temp.packList.forEach(mitem => {
          temp.money += mitem.detList[0].fee;
        });

        temp.price = temp.packList.reduce(
          (total, currentValue) => total + currentValue.price || total + currentValue.fee || 0,
          0
        );
        temp.pdNameList = getArryStringBySymbol(temp.packList, 'pdNameList', '，');
      });
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 获取详情
    getDetail(state, { payload }) {
      const temp = state;
      const ptemp = payload;
      temp.addOrEdit.productList = payload.productData;
      if (payload.detailData && payload.detailData.areaList && payload.detailData.areaList.length) {
        ptemp.detailData.areaNameList = getArryStringBySymbol(
          payload.detailData.areaList,
          'areaName'
        );
        const areaListFormat = [];
        payload.detailData.areaList.forEach(item => {
          areaListFormat.push({
            key: item.areaId,
            label: item.areaName,
          });
        });
        ptemp.detailData.areaListFormat = areaListFormat;
      }
      if (
        payload.detailData &&
        payload.detailData.affixList &&
        payload.detailData.affixList.length
      ) {
        const fileListFormat = [];
        payload.detailData.affixList.forEach(item => {
          fileListFormat.push({
            uid: item.fileId,
            url: `/nsApi/fileServer/downloadFile?fileId=${item.fileId}&fileName=${item.fileName}`,
            name: item.fileName,
            linkProps: { download: `${item.fileName}` },
          });
        });
        ptemp.detailData.fileListFormat = fileListFormat;
      }
      if (payload && payload.detailData && payload.detailData.packList) {
        payload.detailData.packList.forEach(items => {
          const t1 = items;
          t1.price = t1.detList.reduce(
            (total, currentValue) => total + currentValue.price || total + currentValue.fee || 0,
            0
          );
          t1.pdNameList = getArryStringBySymbol(t1.detList, 'pdName', '+');
        });
      }

      return {
        ...state,
        detail: payload.detailData,
        addOrEdit: state.addOrEdit, // 该数据下的产品组合
      };
    },
    // 获取产品列表
    getProductList(state, { payload }) {
      return {
        ...state,
        addOrEdit: { ...state.addOrEdit, productList: payload },
      };
    },
    // 获取操作历史
    getHistory(
      state,
      {
        payload: { data, currentPage, pageSizes },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        history: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize: pageSizes },
        },
      };
    },
    // 清空数据
    // eslint-disable-next-line no-unused-vars
    clearData(state, { payload }) {
      return {
        ...state,
        detail: {
          detList: [],
          affixList: [],
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
}
export default ModelAddEmp;


